package com.eduhzy.ttw.teacher.mvp.presenter;

import android.app.Application;
import android.os.Message;

import com.blankj.utilcode.util.ObjectUtils;
import com.eduhzy.ttw.commonsdk.core.EventBusTags;
import com.eduhzy.ttw.commonsdk.core.RouterHub;
import com.eduhzy.ttw.commonsdk.entity.ClassDetailsData;
import com.eduhzy.ttw.commonsdk.entity.CommonData;
import com.eduhzy.ttw.teacher.mvp.contract.ClassDetailsContract;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;

import org.simple.eventbus.EventBus;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


@ActivityScope
public class ClassDetailsPresenter extends BasePresenter<ClassDetailsContract.Model, ClassDetailsContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public ClassDetailsPresenter(ClassDetailsContract.Model model, ClassDetailsContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void getClassInfoById(String classId) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("id", classId);
        mModel.getClassInfoById(map)
                .subscribeOn(Schedulers.io())
                //遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                .retryWhen(new RetryWithDelay(3, 2))
                .doOnSubscribe(disposable -> {
                    //显示下拉刷新的进度条
                    mRootView.showLoading();
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    //隐藏下拉刷新的进度条
                    mRootView.hideLoading();
                })
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<ClassDetailsData>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<ClassDetailsData> commonData) {
                        if (commonData.isResult()) {
                            mRootView.update(commonData.getData());
                        }
                    }
                });
    }

    public void dropClass(String baseNo, String id) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("classId", baseNo);
        map.put("userId", id);
        mModel.dropClass(map)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(2, 3))
                .doOnSubscribe(disposable -> {
                    //显示下拉刷新的进度条
                    mRootView.showTipLoading(true);
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    //隐藏下拉刷新的进度条
                    mRootView.showTipLoading(false);
                })
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<Map>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<Map> commonData) {
                        if (commonData.isResult()) {
                            mRootView.showMessage(ObjectUtils.isEmpty(commonData.getMessage()) ? "退出成功" : commonData.getMessage());
                            mRootView.killMyself();
                            Message msg = Message.obtain();
                            msg.what = EventBusTags.DELETE_CLASS_SUCCESS;
                            EventBus.getDefault().post(msg, RouterHub.APP_MINECLASSACTIVITY);
                        } else {
                            mRootView.showMessage(commonData.getMessage());
                        }
                    }
                });
    }

    public void getTargetByQrCode(String joinId, String userId) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("qrCode", joinId);
        map.put("userId", userId);
        mModel.getTargetByQrCode(map)
                .subscribeOn(Schedulers.io())
                //遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                .retryWhen(new RetryWithDelay(3, 2))
                .doOnSubscribe(disposable -> {
                    //显示下拉刷新的进度条
                    mRootView.showLoading();
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    //隐藏下拉刷新的进度条
                    mRootView.hideLoading();
                })
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<ClassDetailsData>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<ClassDetailsData> commonData) {
                        if (commonData.isResult()) {
                            mRootView.update(commonData.getData());
                        } else {
                            mRootView.showMessage(commonData.getMessage());
                            mRootView.killMyself();
                        }
                    }
                });
    }

    public void applyClass(String classId, String id) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("classId", classId);
        map.put("userId", id);
        mModel.applyClass(map)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(2, 3))
                .doOnSubscribe(disposable -> {
                    //显示下拉刷新的进度条
                    mRootView.showTipLoading(true);
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    //隐藏下拉刷新的进度条
                    mRootView.showTipLoading(false);
                })
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<Map>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<Map> commonData) {
                        if (ObjectUtils.isNotEmpty(commonData.getMessage())) {
                            mRootView.showMessage(commonData.getMessage());
                        }
                        if (commonData.isResult()) {
                            Message msg = Message.obtain();
                            msg.what = EventBusTags.DELETE_CLASS_SUCCESS;
                            EventBus.getDefault().post(msg, RouterHub.APP_MINECLASSACTIVITY);
                            mRootView.killMyself();
                        }
                    }
                });
    }
}
